package rwt.server.handlers.web;

import org.slf4j.*;

import rwt.server.*;
import rwt.server.RailroadMessages.DoLocoInitMsg;
import rwt.server.WebMessages.DoInitializeTrain;
import rwt.server.core.*;

public class DoInitializeTrainHandler extends MessageHandler<DoInitializeTrain>
{
	private static final Logger logger = LoggerFactory.getLogger(DoInitializeTrainHandler.class);
	
	@Override
	public void handle(DoInitializeTrain message, IConnection source) throws Exception
	{
		logger.info("DoInitTrain is being handled...");
		
		RailServer.getTrainManager().getTrainById(message.trainId)
				.setInitializationData((IClient) source, message.headSensor, message.tailSensor);
		
		DoLocoInitMsg railMsg = new DoLocoInitMsg();
		railMsg.locoAddress = message.trainId;
		
		// Expand the head/tail sensor pair to include any intermediate sensors
		railMsg.sensors = RailServer.getTrackLayout().expandPair(message.headSensor, message.tailSensor);
		
		RailServer.getController().write(railMsg);
	}
}
